#include <QSettings>
#include <QDataStream>
#include "tmclientthread.h"

#include "TeaMakerMsg.h"
//
CTMClientThread::CTMClientThread() 
	: QThread(),
	m_pSocket(NULL)
{
	QSettings settings;
	
	QString strServerAddress = settings.value("config/serverAddress").toString();
	int nServerPort = settings.value("config/serverPort").toInt();
	
	// create socket:
	m_pSocket = new QTcpSocket();
	m_pSocket->connectToHost(strServerAddress, nServerPort);
	
	connect(m_pSocket, SIGNAL(connected()), this, SLOT(connected()), Qt::QueuedConnection);
	connect(m_pSocket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection);
	connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::QueuedConnection);
}
//

void CTMClientThread::run()
{
	qWarning() << "Client Thread Running";
	
	m_pTickTimer = new QTimer;
	m_pTickTimer->setInterval(100);
	connect(m_pTickTimer, SIGNAL(timeout()), this, SLOT(tick()));
	
	m_pPingTimer = new QTimer;
	m_pPingTimer->setInterval(1000);
	connect(m_pPingTimer, SIGNAL(timeout()), this, SLOT(sendPingMessage()));
	
	m_pTickTimer->start();
	m_pPingTimer->start();
	
	exec();
}

void CTMClientThread::connected()
{
	qWarning() << Q_FUNC_INFO << "Connected";
}

void CTMClientThread::disconnected()
{
	qWarning() << Q_FUNC_INFO << "Disconnected";
}

void CTMClientThread::readyRead()
{
	// (1) Make sure that there's the data size availoable:
	while (m_pSocket->bytesAvailable() < sizeof(quint32));
	
	QDataStream reader(m_pSocket);
	quint32 nDataSize = 0;
	reader >> nDataSize;
	
	qWarning() << "Recieved" << nDataSize << "Bytes of data";
	
	while (m_pSocket->bytesAvailable() < nDataSize);
	
	// get message:
	CTeaMakerMsg *const pTeaMakerMsg = CTeaMakerMsg::getMessageFromDataStream(reader);
	
	m_incomingMessages.append(pTeaMakerMsg);
}

void CTMClientThread::tick()
{
	// check input queue:
	if (! m_incomingMessages.empty())
	{
		CTeaMakerMsg *pMessage = m_incomingMessages.dequeue();
		
		switch (pMessage->getMessageType())
		{
			case CTeaMakerMsg::PingMessage:
			{
				qWarning() << "Got reply to ping message.";
			}
		}
		delete pMessage;
	}
	
	// check the output queue:
	if (! m_outgoingMessages.empty())
	{
		CTeaMakerMsg *pMessage = m_outgoingMessages.dequeue();
		if (pMessage)
		{
			QDataStream writer(m_pSocket);
			pMessage->serialiseMessage(writer, true);
			delete pMessage;
		}
	}
}

void CTMClientThread::sendPingMessage()
{
	CTeaMakerPingMsg *pPingMsg = CTeaMakerMsg::createPingMessage();
	if (pPingMsg)
	{
		qWarning() << "Sending ping message";
		m_outgoingMessages.enqueue((CTeaMakerMsg*)pPingMsg);
	}
}

